package com.mall.controller;


import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.mall.model.User;
import com.mall.service.UserService;
import com.mall.shiro.ShiroUtils;

@Controller
public class TestController {
	@Autowired
	private UserService userService;
	
	
	@RequestMapping("login")
	public String login() {
		return "login";
	}
	
	@RequestMapping("index")
	public String index() {
		return "index";
	}
	@RequestMapping(value="/admin")
	@ResponseBody
	public String admin() {
		return "admin success";
	}
	@RequestMapping(value="/userInfo")
	@ResponseBody
	public String userInfo() {
		User user = ShiroUtils.getUserEntity();
		String jsonString = JSON.toJSONString(user);
		return jsonString;
	}
	
	@RequestMapping("unauthorized")
	public String unauthorized() {
		return "unauthorized";
	}
	//看到 3-11
	@RequestMapping("edit")
	@ResponseBody
	public String edit() {
		return "edit success";
	}
	@RequestMapping("logout")
	public String logout() {
		Subject subject=SecurityUtils.getSubject();
		if (subject!=null) {
			subject.logout();
		}
		return "login";
	}
	
	@RequestMapping("loginUser")
	public String loginUser(@RequestParam("username")String username,@RequestParam("password") String password,HttpSession session) {
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject=SecurityUtils.getSubject();
		try {
			subject.login(token);
			User user=(User) subject.getPrincipal();
			session.setAttribute("user", user);
			return "index";
		} catch (Exception e) {
			// TODO: handle exception
			return "login";
		}
	}
	
	@GetMapping("listUser")
	public String listUser() {
		List<User> listUser = userService.listUser();
		return String.valueOf(listUser);
	}
}
